package com.complex.mdb.dao;


import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created with IntelliJ IDEA.
 * User: AGrankin
 * Date: 29.08.13
 * Time: 16:56
 * To change this template use File | Settings | File Templates.
 */
@MessageDriven(mappedName = "testQueue")
public class ComplexMDB implements MessageListener {

    private static Connection conn = null;
    private Statement myStatement = null;


    @Override
    public void onMessage(Message message) {

        TextMessage msg = null;

        try {
            if (message instanceof TextMessage) {
                msg = (TextMessage) message;
                String line = msg.getText();
                //---------------- work with database -------------------------
                conn = DBConnectionPoolUsage.getDBConnection();
                try {
                    myStatement = conn.createStatement();
                    try {
                        myStatement.executeUpdate(line);
                    } catch (Exception e) {
                        new GetDAOBeanException("Can't execute query: ", e);
                    }
                } catch (SQLException e) {
                    new GetDAOBeanException("SQLException! ComplexMDB.execution() Can't create statement!", e);
                } finally {
                    myStatement = null;
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException e) {
                            new GetDAOBeanException("SQLException! ComplexMDB.execution() Closing connection failed!", e);
                        }
                    }
                }
                //---------------- work with database -------------------------
            } else {
                System.out.println("Message of wrong type: " + message.getClass().getName());
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
